<template>
	<up-upload :name="name" :fileList="fileList" :multiple="multiple" :maxCount="maxCount" :previewFullImage="previewFullImage"
		:accept="accept" :disabled="disabled" @afterRead="afterRead" @delete="delFile">
	</up-upload>
</template>

<script lang="ts" setup>
	import { useAppStore } from "@/store";
	import { ref, watch } from "vue";
	import { getToken } from '@/utils/auth';
	import { test } from '@/uni_modules/uview-plus';
	
	const appStore = useAppStore();
	const baseUrl = appStore.baseUrl;
	
	// 定义组件属性
	const emit = defineEmits(["update:modelValue"]);
	const props = defineProps({
		modelValue: {
			type: Array,
			default: [],
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		previewFullImage: {
			type: Boolean,
			default: false,
		},
		multiple: {
			type: Boolean,
			default: false,
		},
		maxCount: {
			type: Number,
			default: 1
		},
		name: {
			type: String,
			default: 'file'
		},
		accept: {
			type: String,
			default: 'image'
		}
	})
	
	const fileList = ref<any>([]);
	const resultList = ref<any>(props.modelValue);
	const uploadName = ref<any>(props.name);
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file);
	  let fileListLen = fileList.value.length;
	  lists.map((item) => {
	    fileList.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await uploadFilePromise(lists[i].url);
	    let item = fileList.value[fileListLen];
	    fileList.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: baseUrl + result,
	    });
		resultList.value.splice(fileListLen, 1, result);
	    fileListLen++;
	  }
	};
	
	const uploadFilePromise = (url) => {
	  return new Promise((resolve, reject) => {
	    let a = uni.uploadFile({
	      url: `${baseUrl}/file/upload`,
	      filePath: url,
	      name: uploadName.value,
		  header: {
		  	'Authorization': 'Bearer ' + getToken()
		  },
	      success: (res) => {
	        setTimeout(() => {
	          resolve(JSON.parse(res.data).data);
	        }, 1000);
	      },
	    });
	  });
	};
	
	const delFile = (index, file, name) => {
		fileList.value.splice(index, 1)
		resultList.value.splice(index, 1)
	}
	
	watch(
		() => resultList.value,
		(newVal) => {
			emit("update:modelValue", newVal);
		},
		{ deep: true }
	);
	
	watch(
		() => props.modelValue,
		(newVal) => {
			fileList.value = newVal.map((item) => {
				return {
					url: baseUrl + item
				}
			})
			resultList.value = newVal;
		},
		{ deep: true }
	);
</script>